package com.mxx.springaction;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import sun.rmi.runtime.Log;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author xiaoxu.ma
 * @date 2021/11/17 18:28
 */
@Component
public class UserService {
    @Resource    // 自动注入，spring boot会帮我们实例化一个对象
    private JdbcTemplate jdbcTemplate;   // 一个通过JDBC连接数据库的工具类，可以通过这个工具类对数据库进行增删改查

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = -1, readOnly = false)
    public void test2() {
        String sql = "INSERT into students (name) values ('aaa')";
        jdbcTemplate.execute(sql);
        int i = 1 / 0;
        String sql2 = "INSERT into students (name) values ('bbb')";
        jdbcTemplate.execute(sql2);
    }

    @Transactional(rollbackFor = Exception.class)
    public void aFunction() {
        String sql = "INSERT into students (name) values ('aaa')";
        aInnerFunction(); // 调用内部没有添加@Transactional注解的函数
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void aInnerFunction() {
        String sql2 = "INSERT into students (name) values ('bbb')";
        int i = 1 / 0;
        throw new RuntimeException("函数执行有异常!");
    }

}
